#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <vector>

#include "inetaddr.hpp"
#include "log.hpp"
using namespace myaddr;
using namespace mylog;
namespace myrounte
{
    class Rounte
    {
        bool Isexist(const InetAddr &peer)
        {
            for (auto &addr : _inetaddr)
            {
                if (addr == peer)
                    return true;
            }
            return false;
        }

    public:
        Rounte() {}
        ~Rounte() {}
        void Massage_Rounte(int sockfd, const std::string &massage, const InetAddr &peer)
        {
            if (Isexist(peer) == false)
            {
                // 新增在线client
                _inetaddr.push_back(peer);
                LOG(Level::DEBUG) << "新增一个在线client " << peer.GetString();
            }
            // 发送信息给所有在线client
            std::string news = peer.GetString() + " say#" + massage;
            for (auto &addr : _inetaddr)
            {
                int n = sendto(sockfd, news.c_str(), news.size(), 0, addr.GetInet(), addr.Len());
                if (n < 0)
                {
                    LOG(Level::DEBUG) << "sento error";
                }
            }
            if (massage == "QUIT")
            {
                // client退出
                auto it = _inetaddr.begin();
                while (it != _inetaddr.end())
                {
                    if (*it == peer)
                        break;
                    it++;
                }
                _inetaddr.erase(it);
                LOG(Level::DEBUG) << "client退出";
            }
        }

    private:
        std::vector<InetAddr> _inetaddr;
    };
}